import random

import base64
from io import BytesIO
from PIL import Image,ImageDraw,ImageFont,ImageFilter
from flask import *
api = Blueprint('api', __name__, url_prefix='/api')

@api.route('/loginCode', methods=('GET', 'POST'))
def loginCode():
    number = 5
    code =''
    for a in range(number):
        code = code + str(random.randint(0,9))
    width,height = (130,38)
    image = Image.new('RGBA',(width,height),(255,255,255))
    font = ImageFont.truetype('AxureHandwriting.otf',35)
    draw = ImageDraw.Draw(image)
    font_width, font_height = font.getsize(code)
    draw.text((20, 5),code,
        font= font,fill=(0,0,0))
    for a in range(4):
        on = (random.randint(0, width), random.randint(0, height))
        end = (random.randint(0, width), random.randint(0, height))
        draw.line([on, end], fill = (0,0,0))
    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #滤镜，边界加强
    buf = BytesIO()
    image.save(buf, 'png')
    buf_str = buf.getvalue()
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/gif'
    # session['imageCode'] = code
    return response

@api.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        loginCode = request.form['loginCode']
        if loginCode==session['imageCode'].lower():
            pass
        else:
            return jsonify({'code':-1,'msg':'图片验证码错误'})
    
    
    